import { BaseResponse } from '@/common/BaseResponse';
import { DynamicComment } from '@/entity/dynamic-comment.entity';
import { DynamicFollow } from '@/entity/dynamic-follow.entity';
import { DynamicLike } from '@/entity/dynamic-like.entity';
import { DynamicReply } from '@/entity/dynamic-reply.entity';
import { Dynamic } from '@/entity/dynamic.entity';
import { IntegralTask } from '@/entity/integral-task.entity';
import { StudyMatchResult } from '@/entity/study-match-result.entity';
import { User } from '@/entity/user.entity';
import { FINISH_STATUS, RECORD_STATUS } from '@/enum/common';
import {
  DNYMIC_LIKE_STATUS,
  DYNAMIC_LIKE_TYPE,
  FOLLOW_STATUS,
} from '@/enum/dynamic';
import { HTTP_CUSTOM_CODE } from '@/enum/http-custom-code';
import { TASK_LIST } from '@/enum/study-match';
import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { StudyMatchService } from '../study-match/study-match.service';
import { DynamicDto } from './dto/dynamic.dto';
import { LoveDto } from './dto/love.dto';
import { PageParamDto } from './dto/page-param.dto';

@Injectable()
export class DynamicService {
  constructor(
    @InjectRepository(Dynamic)
    private readonly dynamicRepository: Repository<Dynamic>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(DynamicLike)
    private readonly dynamicLikeRepository: Repository<DynamicLike>,
    @InjectRepository(DynamicComment)
    private readonly dynamicCommentRepository: Repository<DynamicComment>,
    @InjectRepository(DynamicReply)
    private readonly dynamicReplyRepository: Repository<DynamicReply>,
    @InjectRepository(DynamicFollow)
    private readonly dynamicFollowRepository: Repository<DynamicFollow>,
    @InjectRepository(StudyMatchResult)
    private readonly studyMatchResultRepository: Repository<StudyMatchResult>,
    @InjectRepository(IntegralTask)
    private readonly integralTaskRepository: Repository<IntegralTask>,
  ) {}

  /**
   * 创建动态
   */
  async create(dynamicDto: DynamicDto & { userId: number }) {
    const dynamic = new Dynamic();
    Object.assign(dynamic, dynamicDto);
    const result = await this.dynamicRepository.save(dynamic);
    await this.addStudyMatchScore(dynamic.userId, 10, TASK_LIST.PUBLISH);
    return result;
  }

  async addStudyMatchScore(id: number, num: number, type: number) {
    // 您是否已被匹配
    const matchResultMessage = await this.studyMatchResultRepository.findOne({
      where: [
        {
          matchOne: id,
        },
        {
          matchTwo: id,
        },
      ],
    });

    if (!matchResultMessage) {
      return;
    }

    // 判断今日是否完成任务
    const qb = this.integralTaskRepository.createQueryBuilder('integralTask');
    const result = await qb
      .andWhere('match_id = :matchId and task_type = :type', {
        matchId: matchResultMessage.id,
        type: type,
      })
      .andWhere('to_days(create_time) = to_days(now())')
      .getOne();
    console.log('JSON.stringify(result)', JSON.stringify(result));

    if (result) {
      return;
    }
    const integralTask = new IntegralTask();
    integralTask.matchId = matchResultMessage.id;
    integralTask.taskType = type;
    integralTask.integral = num;
    integralTask.status = FINISH_STATUS.FINISHED;
    await this.integralTaskRepository.save(integralTask);

    matchResultMessage.integral += num;
    return this.studyMatchResultRepository.update(
      matchResultMessage.id,
      matchResultMessage,
    );
  }

  async getDyamicList(pageParamDto: PageParamDto) {
    const qb = this.dynamicRepository.createQueryBuilder('dynamic');
    let result = qb;
    console.log('pageParamDto', pageParamDto);

    if (pageParamDto.type) {
      result = qb.andWhere('dynamic.type = :type', {
        type: pageParamDto.type,
      });
    }
    if (pageParamDto.lastId) {
      result = qb.andWhere('dynamic.id <= :id', {
        id: pageParamDto.lastId,
      });
    }
    result
      .andWhere('dynamic.status = :status', {
        status: RECORD_STATUS.SHOW,
      })
      .leftJoinAndMapOne(
        'dynamic.userInfo',
        User,
        'user',
        'user.id = dynamic.user_id',
      )
      .addOrderBy('dynamic.create_time', 'DESC')
      .limit(pageParamDto.size)
      .offset((pageParamDto.current - 1) * pageParamDto.size);
    const total = await result.getCount();
    const list = await result.getMany();
    // for (let i = 0; i < list.length; i++) {
    //   list[i].love = await this.dynamicLikeRepository.count({
    //     where: {
    //       likeTargetId: list[i].id,
    //       likeType: DYNAMIC_LIKE_TYPE.DYNAMIC,
    //     },
    //   });
    //   const commentCount = await this.dynamicCommentRepository.count({
    //     where: {
    //       commentDynamicId: list[i].id,
    //     },
    //   });

    //   const replyCount = await this.dynamicReplyRepository.count({
    //     where: {
    //       dynamicId: list[i].id,
    //     },
    //   });
    //   list[i].comment = commentCount + replyCount;
    // }
    return BaseResponse.toSuccesJustData({
      current: Number(pageParamDto.current),
      list,
      size: Number(pageParamDto.size),
      total,
    });
  }

  async getDynamicDetail(id: number, userId: number) {
    const detail = await this.dynamicRepository.findOne({
      where: {
        id,
        status: RECORD_STATUS.SHOW,
      },
    });

    if (!detail) {
      throw new HttpException('动态不存在', HTTP_CUSTOM_CODE.DYNAMIC_NOT_FOUND);
    }
    const userInfo = await this.userRepository.findOne({
      where: {
        id: detail.userId,
      },
    });
    detail.userInfo = userInfo;

    // 浏览量+1
    detail.views += 1;
    const updateDynamic = {
      ...detail,
    };
    delete updateDynamic.id;
    delete updateDynamic.userInfo;
    const result = Object.assign({}, detail, new Dynamic());
    result.love = await this.dynamicLikeRepository.count({
      where: {
        likeTargetId: result.id,
        likeType: DYNAMIC_LIKE_TYPE.DYNAMIC,
        status: DNYMIC_LIKE_STATUS.LIKED,
      },
    });
    const commentCount = await this.dynamicCommentRepository.count({
      where: {
        commentDynamicId: result.id,
      },
    });

    const loveRecord = await this.dynamicLikeRepository.findOne({
      where: {
        likeTargetId: result.id,
      },
    });

    if (loveRecord) {
      result.loveStatus = loveRecord.status;
    } else {
      result.loveStatus = 0;
    }

    const replyCount = await this.dynamicReplyRepository.count({
      where: {
        dynamicId: detail.id,
      },
    });
    result.comment = commentCount + replyCount;

    if (!userId) {
      console.log('userId', userId);
      result.followStatus = FOLLOW_STATUS.NOT_FOLLOW;
    } else {
      const followResult = await this.dynamicFollowRepository.findOne({
        where: {
          userId: userId,
          targetUserId: result.userId,
        },
      });
      console.log('followResult', followResult);
      if (followResult) {
        result.followStatus = followResult.status;
      } else {
        result.followStatus = FOLLOW_STATUS.NOT_FOLLOW;
      }
    }

    await this.dynamicRepository.update(id, updateDynamic);
    return result;
  }

  async toLove(loveDto: LoveDto) {
    // 查询动态是否存在
    const dynamicResult = await this.dynamicRepository.findOne({
      where: {
        id: loveDto.dynamicId,
      },
    });
    if (!dynamicResult) {
      throw new HttpException(
        '动态不存在！',
        HTTP_CUSTOM_CODE.DYNAMIC_NOT_FOUND,
      );
    }
    // 查询是否已点赞
    const result = await this.dynamicLikeRepository.findOne({
      where: {
        likeType: DYNAMIC_LIKE_TYPE.DYNAMIC,
        likeTargetId: loveDto.dynamicId,
      },
    });

    if (!result) {
      const like = new DynamicLike();
      Object.assign(like, {
        likeType: DYNAMIC_LIKE_TYPE.DYNAMIC,
        likeTargetId: loveDto.dynamicId,
        likeUserId: loveDto.likeUserId,
        status: DNYMIC_LIKE_STATUS.LIKED,
      } as DynamicLike);
      return BaseResponse.toSucces(
        await this.dynamicLikeRepository.save(like),
        '点赞成功',
      );
    }

    if (result.status === DNYMIC_LIKE_STATUS.LIKED) {
      result.status = DNYMIC_LIKE_STATUS.NOT_LIKED;
      await this.dynamicLikeRepository.update(result.id, result);
      return BaseResponse.toSucces(result, '取消点赞成功');
    }

    result.status = DNYMIC_LIKE_STATUS.LIKED;
    await this.dynamicLikeRepository.update(result.id, result);
    return BaseResponse.toSucces(result, '点赞成功');
  }

  async getPersonalDynamicList(pageParamDto: PageParamDto, userId: number) {
    const qb = this.dynamicRepository.createQueryBuilder('dynamic');
    let result = qb.andWhere('dynamic.user_id = :userId', {
      userId,
    });
    console.log('pageParamDto', pageParamDto);

    if (pageParamDto.type) {
      result = qb.andWhere('dynamic.type = :type', {
        type: pageParamDto.type,
      });
    }
    if (pageParamDto.lastId) {
      result = qb.andWhere('dynamic.id <= :id', {
        id: pageParamDto.lastId,
      });
    }
    result
      .leftJoinAndMapOne(
        'dynamic.userInfo',
        User,
        'user',
        'user.id = dynamic.user_id',
      )
      .andWhere('dynamic.status = :status', {
        status: RECORD_STATUS.SHOW,
      })
      .addOrderBy('dynamic.create_time', 'DESC')
      .limit(pageParamDto.size)
      .offset((pageParamDto.current - 1) * pageParamDto.size);
    const total = await result.getCount();
    const list = await result.getMany();
    for (let i = 0; i < list.length; i++) {
      list[i].love = await this.dynamicLikeRepository.count({
        where: {
          likeTargetId: list[i].id,
          likeType: DYNAMIC_LIKE_TYPE.DYNAMIC,
        },
      });
      const commentCount = await this.dynamicCommentRepository.count({
        where: {
          commentDynamicId: list[i].id,
        },
      });

      const replyCount = await this.dynamicReplyRepository.count({
        where: {
          dynamicId: list[i].id,
        },
      });
      list[i].comment = commentCount + replyCount;

      const loveRecord = await this.dynamicLikeRepository.findOne({
        where: {
          likeTargetId: list[i].id,
        },
      });

      if (loveRecord) {
        list[i].loveStatus = loveRecord.status;
      } else {
        list[i].loveStatus = 0;
      }
    }
    return BaseResponse.toSuccesJustData({
      current: Number(pageParamDto.current),
      list,
      size: Number(pageParamDto.size),
      total,
    });
  }
}
